#!/bin/bash

DIR=`dirname $0`
LOCK=${DIR}/.lock
CONF=${DIR}/ctest.conf

if [ -f ${LOCK} ]; then
    touch ${LOCK}
    echo "Another ctest is running. If not, delete ${LOCK}."
    exit 1
fi

touch -t 197001010000 ${LOCK}

# Create subprocess to watch for changes
(
DIR=`dirname $0`
LOCK=${DIR}/.lock
while inotifywait -q -q -s -r -e create,modify,move ${DIR}/../src; do
    touch ${LOCK}
done
) &

# Kill all subprocesses and r$emove the lock if exit
trap "kill 0;rm -f ${LOCK}" SIGINT SIGTERM EXIT

function loadParams() {
    CONF_DT=$(date -r ${CONF} +%s)
    unset JAVA_OPT
    unset JAVAC_OPT
    QUIET=1
    . ${CONF}
}


clear
echo "Continous Test is waiting for changes ..."

loadParams

while test -f ${LOCK} && inotifywait -q -q -e attrib,modify,move ${DIR}; do

    while :
    do
        DATETIME=$(date +%s)
        if [ ${CONF_DT} -lt $(date -r ${CONF} +%s) ]; then
            loadParams
        fi
        clear

        make -C ${DIR}/.. -s test "JAVAC_OPT=${JAVAC_OPT}" "JAVA_OPT=${JAVA_OPT}" "QUIET=${QUIET}"
      
        if [ ! -f ${LOCK} ]; then
            exit 0
        elif [ $(date -r ${LOCK} +%s) -gt ${DATETIME} ]; then
            echo "Change detected ... Re-test in 10 seconds"
            inotifywait -q -q -e attrib,modify,move -t 10 ${DIR}
        else
            break
        fi
    done

done
